<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb
      separator="/"
      class="u-mb20"
    >
      <el-breadcrumb-item>
        <span
          class="c-text-high u-cursor"
          @click="back"
        >权限管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}角色</el-breadcrumb-item>
    </el-breadcrumb>

    <SectionContainer class="u-p20 u-mb40">
      <el-form
        label-width="120px"
        :model="roleData"
        :rules="roleRules"
        ref="roleForm"
      >
        <el-form-item
          prop="name"
          label="角色名称"
        >
          <el-input
            placeholder="请输入角色名称"
            class="u-w450"
            v-model="roleData.name"
            :disabled="pageAction === 'detail'"
          >
          </el-input>
          <ShowWordLimit
            :value="roleData.name"
            :maxlength="20"
          ></ShowWordLimit>
        </el-form-item>
        <el-form-item
          prop="roleType"
          label="角色类型"
        >
          <el-select
            placeholder="请选择角色类型"
            class="u-w450"
            v-model="roleData.roleType"
            :disabled="pageAction === 'detail'"
          >
            <el-option
              :value="2"
              label="管理员"
            ></el-option>
            <el-option
              :value="1"
              label="广告主"
            ></el-option>
          </el-select>
          <Tip
            class="u-ml5"
            inline
            v-if="['create', 'edit'].includes(pageAction)"
          >运营、财务、商务等除广告主外的角色，角色类型请选择管理员</Tip>
        </el-form-item>
        <el-form-item
          prop="remarks"
          label="角色描述"
        >
          <el-input
            type="textarea"
            autosize
            placeholder="请输入角色描述"
            class="u-w450"
            v-model="roleData.remarks"
            :disabled="pageAction === 'detail'"
          >
          </el-input>
          <ShowWordLimit
            :value="roleData.remarks"
            :maxlength="50"
          ></ShowWordLimit>
        </el-form-item>
        <el-form-item label="分配权限">
          <!-- 角色权限 -->
          <div class="u-w400 u-fl">
            <el-tree
              class="role-permission--tree"
              accordion
              show-checkbox
              node-key="id"
              :data="roleTree"
              :default-checked-keys="roleData.checked"
              default-expand-all
              :props="{
              label: 'name'
            }"
              @check="handleRoleTreeCheck"
            >
            </el-tree>
          </div>
          <!-- 进入账户权限 -->
          <div
            class="u-fl"
            v-if="roleData.roleType === 2"
          >
            <div class="u-fl account-permission__label">进入账户后权限</div>
            <el-tree
              class="u-fl u-w400 account-permission--tree"
              accordion
              show-checkbox
              node-key="id"
              :data="enterAccountTree"
              :default-checked-keys="roleData.intoAccountChecked"
              default-expand-all
              :props="{
                label: 'name'
              }"
              @check="handleAccountTreeCheck"
            >
            </el-tree>
          </div>
        </el-form-item>
        <template v-if="pageAction === 'detail'">
          <el-form-item label="角色状态">{{roleData.status === 2 ? "启用" : "停用"}}</el-form-item>
          <el-form-item label="创建人">{{roleData.createBy}}</el-form-item>
          <el-form-item label="创建时间">{{roleData.createDate}}</el-form-item>
          <el-form-item label="最后操作人">{{roleData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间">{{roleData.updateDate}}</el-form-item>
        </template>
      </el-form>
    </SectionContainer>

    <div class="u-affix-bottom u-page-handle">
      <el-button
        size="small"
        type="primary"
        v-if="['create', 'edit'].includes(pageAction)"
        @click="handleSubmit"
      >确定</el-button>
      <el-button
        size="small"
        @click="back"
      >返回</el-button>
    </div>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";

import SectionContainer from "@/components/section-container";
import Tip from "@/components/tip";
import ShowWordLimit from "@/components/show-word-limit";

import { getStrLen } from "@/utils";
import {
  fetchOtherRoleTree,
  fetchOtherRoleDetail,
  fetchOtherRoleAdd,
  fetchOtherRoleUpdate
} from "@/api";

import permissionMixin from "@/mixins/permission";

export default {
  mixins: [permissionMixin],
  components: {
    SectionContainer,
    Tip,
    ShowWordLimit
  },
  data() {
    return {
      pageAction: this.$route.query.action,
      // 分配权限
      roleTree: [],
      enterAccountTree: [],
      roleData: {
        name: "",
        remarks: "",
        roleType: "",
        checked: [],
        intoAccountChecked: []
      },
      roleRules: {
        name: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入角色名称"));
            } else if (getStrLen(value) > 20) {
              callback(new Error("角色名称不能超过20个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        roleType: {
          required: true,
          message: "请选择角色类型",
          trigger: ["blur", "change"]
        },
        remarks: {
          validator: (rule, value, callback) => {
            if (getStrLen(value) > 50) {
              callback(new Error("角色描述不能超过50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "创建",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    // 设置树disabled
    setTreeDisabled(data) {
      data.forEach(item => {
        item.disabled = true;
        if (item.children && item.children.length) {
          this.setTreeDisabled(item.children);
        }
      });
      return data;
    },
    // 确定
    handleSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          if (this.pageAction === "create") {
            this.fetchOtherRoleAdd();
          } else if (this.pageAction === "edit") {
            this.fetchOtherRoleUpdate();
          }
        } else {
          return false;
        }
      });
    },
    // 角色详情
    fetchOtherRoleDetail() {
      fetchOtherRoleDetail({
        query: {
          id: this.$route.query.id
        }
      }).then(res => {
        this.roleData = res.data;
      });
    },
    // 更新角色
    fetchOtherRoleUpdate() {
      fetchOtherRoleUpdate({
        body: this.roleData
      }).then(() => {
        this.$message({
          message: "角色修改成功",
          duration: 1000
        });
        setTimeout(() => {
          this.back();
        }, 1000);
      });
    },
    // 新建角色
    fetchOtherRoleAdd() {
      fetchOtherRoleAdd({
        body: this.roleData
      }).then(() => {
        this.$message({
          message: "角色创建成功",
          duration: 1000
        });
        setTimeout(() => {
          this.back();
        }, 1000);
      });
    },
    // 配置权限
    handleRoleTreeCheck(current, { checkedKeys }) {
      this.roleData.checked = checkedKeys;
    },
    handleAccountTreeCheck(current, { checkedKeys }) {
      this.roleData.intoAccountChecked = checkedKeys;
    },
    // 获取进入账户的权限树
    getEnterAccountTree(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].isShow !== "1") {
          data.splice(i, 1);
          i--;
        } else {
          if (data[i].children && data[i].children.length) {
            this.getEnterAccountTree(data[i].children);
          }
        }
      }
      return data;
    },
    // 获取默认选中数的项
    getDefaultChecked(data, checked = []) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children) {
          this.getDefaultChecked(data[i].children, checked);
        } else {
          checked.push(data[i].id);
        }
      }
      return checked;
    },
    // 权限树
    fetchOtherRoleTree() {
      return fetchOtherRoleTree().then(res => {
        this.roleTree = res.data.data || [];
        this.enterAccountTree = this.getEnterAccountTree(
          cloneDeep(res.data.data)
        );
        // 默认选中
        if (this.pageAction === "create") {
          this.roleData.intoAccountChecked = this.getDefaultChecked(this.enterAccountTree);
        }
        // 详情禁用
        else if (this.pageAction === "detail") {
          this.roleTree = this.setTreeDisabled(this.roleTree);
          this.enterAccountTree = this.setTreeDisabled(this.enterAccountTree);
        }
      });
    },
    // 返回
    back() {
      this.$router.replace({
        name: "other-role"
      });
    }
  },
  created() {
    this.fetchOtherRoleTree().then(() => {
      if (["detail", "edit"].includes(this.pageAction)) {
        this.fetchOtherRoleDetail();
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.role-permission--tree,
.account-permission--tree {
  margin-top: 7px;
}
.account-permission__label {
  color: #606266;
  font-size: 14px;
  padding-right: 12px;
}
</style>